package org.displayextended
{
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import org.vo.ModalVO;

	/**
	 * Solid that is drawn in to block mouse events that may occur during the 
	 * loading and / or animation of objects.
	 * 
	 * This class won't cover keyboard events, so you better have something else
	 * on hand to deal with them!
	 * 
	 * @author zachary.seabrook
	 * 
	 */	
	public class Modal extends Sprite
	{
		// Trace shortcut method and toggle property
		public var showTrace:Boolean = false;
		public function t( ...rest ):void{ if( showTrace) trace( this, rest ); }
		
		private var _vo:ModalVO;
		
		public var drawX : Number;
		public var drawY : Number;
		public var drawWidth : Number;
		public var drawHeight : Number;
		
		public var modalColor:uint;
		public var modalAlpha:Number;	
		
		public var useFade:Boolean = true;
		public var fadeIncr:Number = .1;
		
		public function Modal( ModalValueObject:ModalVO=null )
		{
			!ModalValueObject ? _vo = new ModalVO : _vo = ModalValueObject;
				
			drawX = _vo.x;
			drawY = _vo.y;
			drawWidth = _vo.width;
			drawHeight = _vo.height;
			modalColor = _vo.color;
			modalAlpha = _vo.alpha;
		}
		
		public function draw( event:TimerEvent=null ):void
		{
			if( stage != null )
			{
				graphics.beginFill( modalColor, modalAlpha );
				graphics.drawRect( drawX, drawY, drawWidth, drawHeight );
		    	graphics.endFill();
				
				if( useFade && modalAlpha != 0 )
				{
					alpha = 0;
					fadeIn();
				}
				
		    	if( event )
		    	{
		    		event.target.removeEventListener( TimerEvent.TIMER, draw );
		    		event.target.stop();
		    	}
		 	}
		 	else if( !event )
		 	{
		 		var drawTimer:Timer = new Timer(100);
		 		drawTimer.addEventListener( TimerEvent.TIMER, draw );
		 		drawTimer.start();
		 	}
		}
		
		public function clear():void
		{
			if( !useFade || modalAlpha == 0 )
				graphics.clear();
			else
				fadeOut();
		}
		
		private function fadeIn( event:TimerEvent=null ):void
		{
			if( event )
			{
				if( alpha < 1 )
					alpha += fadeIncr;
					
				if( alpha >= 1 )
				{
					event.target.stop();
					event.target.removeEventListener( TimerEvent.TIMER, fadeIn );
					alpha = 1;
				}
			}
			else
			{
				var fTimer:Timer = new Timer( 100 );
				fTimer.addEventListener( TimerEvent.TIMER, fadeIn );
				fTimer.start();
			}
		}
		
		private function fadeOut( event:TimerEvent=null ):void
		{
			if( event )
			{
				if( alpha > 0 )
					alpha -= fadeIncr;
					
				if( alpha <= 0 )
				{
					event.target.stop();
					event.target.removeEventListener( TimerEvent.TIMER, fadeOut );
					graphics.clear();
					alpha = 1;
				}
			}
			else
			{
				var fTimer:Timer = new Timer( 100 );
				fTimer.addEventListener( TimerEvent.TIMER, fadeOut );
				fTimer.start();
			}
		}
	}
}